//
//  订单提交Ctr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/8.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import soapp
//import TPKeyboardAvoiding
// import mosdks

public enum GoodsBuyType{
    case cartGoods([String])
    case oneGoods([String:Any])
}


open class IntegralOptionBar:JoView{

    
    public var mode:IntegralMode = .none{
        didSet{
            switch mode {
            case .full(let n,open:let op):
                hConstrain.constant = 44
                setNeedsLayout()
                layoutIfNeeded()
                self.alpha = 1
                switcher.isOn = op
            case .integral(let n,open:let op):
                hConstrain.constant = 44
                setNeedsLayout()
                layoutIfNeeded()
                self.alpha = 1
                switcher.isOn = op
            default:
                hConstrain.constant = 0
                setNeedsLayout()
                layoutIfNeeded()
                self.alpha = 0
            }
            label.attributedText = mode.description
            changeMode(mode,mo.model)
        }
    }

    var hConstrain = NSLayoutConstraint()
    let hView = UIView()
    
    let switcher = UISwitch()
    let label = UILabel()
    
    var changeMode:(_:IntegralMode,_:NSMutableDictionary)->Void = {_,_ in}
    

    open override func addLayoutRules() {
        let ls  = self.setEeLays(lays: [
            [hView,[ee.T.L.B],"0"]
        ])
        if let c = ls.1.last{
            hConstrain = c
        }
        alpha = 0
        
        let line = UIView()
        line.backgroundColor = ._separator
        eelay = [
            [line,[ee.T.L.R],"\(TP.separatorHeight)"],
            [switcher,[ee.Y.L,[0,CGFloat.hpadding]]],
            [label,[ee.Y.R,[0,-CGFloat.hpadding]]]
        ]
        switcher.onTintColor = ___shop.tint
        let scale = switcher.transform.scaledBy(x: 0.75, y: 0.75) ;
        switcher.transform = scale
        backgroundColor = ._background
        
        label.attributedText = "开启".ui.color(color: ___shop.tint).font13.astring + "100积分".ui.bfont15.color(color: ___shop.tint).astring + " + 现金兑换购买".ui.color(color: ___shop.tint).font13.astring
        
 
//        mode = .full(700, open: true)
        mode = .none
        switcher.addTarget(self, action: #selector(changeToggle(sender:)), for: .valueChanged)
        
    }
    
    @objc func changeToggle(sender:UISwitch){
        switch mode {
        case .full(let n, open: let op):
            mode = .full(n, open: switcher.isOn)
        case .integral(let n, open: let op):
            mode = .integral(n, open: switcher.isOn)
        default:
            mode = .none
        }
       
        
    }
    
    
}




open class SCOrderSubmitCtr: ListController {
    public var buyType:GoodsBuyType = .oneGoods([String:Any]())
    
    public var remark1:[String:Any]? = nil
    
    public var buySections = NSMutableArray()
    
    public var sellers:NSMutableArray{
        get{
            let sellerList = DataNode.path(node: "list", mo.detail, value: NSMutableArray())
            buySections = sellerList.mutable_array
            let secs = NSMutableArray()
            
            
            remark1 = nil
            weak var wself = self
            sellerList.list { (one:NSMutableDictionary, i) in
                var hasVipAccountBind = false
                //                secs.add(["id":"line8"])
                var goods = NSMutableArray()
                let _goods = one.object(forKey: "goods")
                if let list = _goods as? NSMutableArray{//普通商品接口
                    goods = list
                }
                if let obj = _goods as? NSMutableDictionary{//团购商品接口
                    goods.add(obj)
                }
                
//                one["goods"] = ""
                one["cellID"] = "seller"
                secs.add(one)
                
                goods.list({[weak self] (item:NSMutableDictionary, j) in
                    item["cellID"] = "goods"
                    if(item["zsyx_goods",""]=="1"){
                        hasVipAccountBind = true
                    }
                    secs.add(item)
                })
                
                if let ws = wself
                {
                    if ws.mo.detail[Goods.key_needAddress,false.tag] == true.tag
                    {
                        let wuliu = DataNode.path(node: "dispatch_list", one, value: NSMutableDictionary())
                        wuliu["cellID"] = "wuliu"
                        secs.add(wuliu)
                    }
                }
                
                let mark = [
                    "cellID":"mark",
                    "title":"备注留言".loc,
                    FK.fields:[
                        [
                            FK.placeholder:"填写备注留言".loc,
                            //                                FK.value:mo.model["remark",""],
                            FK.field:StrField(id: "remark\(i)", defaultV: nil, need: false, hiden: false, rule:
                                JoRule(reg: "^[\\s\\S]{0,1000}$", nil_msg: "检查备注留言".loc, err_msg: "请检备注留言".loc))
                        ]
                        ],
                    ].mutable_dictionary
                secs.add(mark)

                
                if(hasVipAccountBind){
                    let ext = OrderExtra.bindzsyx
                    for f in ext.fields(index: i){
                        secs.add(f)
                    }
                }
              
                secs.add(["cellID":"onesellerPrice","__model":one.mutable_dictionary].mutable_dictionary)
                
            }
            return secs
        }
    }
    
    open var sections:TP.section{
        get{
            let spec = GoodsSpec(goods: mo.detail)
            let sec:TP.section = [
                spec.uisection_address,
                [],
//                [
//                    ["id":"line30"],
//                ],
                [
//                    [
//                        "title":"选择支付方式".loc,
//                        "cellID":"payMethod",
//                        FK.fields:[
//                            [
//                                FK.value:PayMethod.defaultMethod.rawValue,
//                                FK.options:PayMethod.payOptions,
//                                FK.field:StrField(id: "paytype", defaultV: nil, need: false, hiden: false, rule:
//                                    JoRule(reg: "^[\\s\\S]{0,200}$", nil_msg: "请选择支付方式".loc, err_msg: "请选择支付方式".loc))
//                            ]
//                        ],
//                    ],
                ],
                spec.uisection_verification_person,
            ]
            return sec
        }
    }
    var isZsyxBind:Bool{
        get{
            return true
        }
    }
    
    
    open var selector:TP.selector{
        get{
            let sel:TP.selector = [
                "cellID<address>":AdressCell.self,
                "cellID<discount>":DiscountInfoCell.self,
                "id<line30>":BlankLine<line.px30>.self,
                "id<line8>":BlankLine<line.px8>.self,
                "id<line4>":BlankLine<line.px4>.self,
                "cellID<goods>":GoodsCell.self,
                "cellID<seller>":SellerCell.self,
                "cellID<wuliu>":WuliuCell.self,
                "cellID<onesellerPrice>":OneSellerPriceCell.self,
                "cellID<mark>":SimpleTextCell.self,
                "cellID<offlinenote>":OfflineNoteCell.self,
                "cellID<name,mobile>":SimpleTextCell.self,
                "cellID<input>":SimpleTextCell.self,
                "cellID<payMethod>":PayCell<PayKit>.self,
                //针对核销地址改的
                "cellID<verifyAddress>":GoodsVerification.AddressCell.self,
                "cellID<verifyAddressTitle>":GoodsVerification.TitleCell.self,
                "cellID<blank>":BlankLine<line.px8>.self,
                "<default>":BlankLine<line.px8>.self,

            ]
            return sel + OrderExtra.cellSelector
        }
    }
    
    let bottomBar = SubmitBar()
    public var wuliu_id = ""
    open override func viewDidLoad() {
        tableView = TPKeyboardAvoidingTableView(frame: .zero, style: .plain)
        super.viewDidLoad()
        FieldCell.name_width = 70
        
        title = "提交订单".loc
        tableView.buildDynamicHeight(height: 80)
        tableView.separatorStyle = .none
        tableView.backgroundColor = ._tableBackground
        mo_request_send()
        weak var wself = self
        __notice.observer(FK.Notice.valueChange) { (notyType, notify) in
            guard let obj = notify.object as? UIViewController,let ws = wself else{return}
            if obj !== ws{
                return
            }
            
        }
        bottomBar.confirmBt.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
//        print("===JJJJJ_---",presentType)
    }
    
    @objc func submitAction(){
        
        var params = [String:Any]()
        if mo.detail[Goods.key_needAddress,false.tag] == true.tag
        {
            let addressID = tableView.model["section0.1.address.id",""]
            if addressID.len < 1
            {
                "请选择收货地址".loc.alert()
                return
            }
            params["addressid"] = addressID
        }
        
        let info = JoPaw.paw(tableView: tableView)
        if !info.validate{
            return
        }
        
        params = info.values + params
        
        var goods_list = [[String:Any]]()
        var marks = [[String:Any]]()
        
        var mark_origin = info.values.mutable_dictionary
        
        //扩展字段
        let keys = mark_origin.allKeys
        for k in keys {
            let skey = "\(k)"
            if skey.hasPrefix("extra_"){
                let nodes = skey.split(separator: "_")
                let validKey = nodes[1]
                let strIndex = nodes[2]
                let index = Int(strIndex) ?? 0
                if let v = mark_origin[k]{
                    mark_origin.removeObject(forKey: k)
                    mark_origin.setValue(v, forKey: "\(validKey)_\(index)")
                }
                
            }
        }
        
//        print("------|\(mark_origin)")
        
        buySections.list {[weak self] (seller:NSMutableDictionary, i) in
            
            if let remarkFields = OrderExtra.extraRemarkKeys(data: mark_origin, index: i){
                var remarkObj:[String:Any] = [:]
                for extraMarkedKey in remarkFields {
                    let validExtraKey = extraMarkedKey.split(separator: "_")[0]
                    remarkObj["\(validExtraKey)"] = mark_origin[extraMarkedKey,""]
                    params.removeValue(forKey: "extra_\(extraMarkedKey)")
//                    remarkObj[]
                }
                remark1 = remarkObj
                
//                marks.append(
//                    [
//                        "merchid":seller["id",""],
//                        "remark":remarkObj
//                    ]
//                )
            }else{
//                marks.append(
//                    [
//                        "merchid":seller["id",""],
//                        "remark":mark_origin["remark\(i)",""]
//                    ]
//                )
            }
            marks.append(
                [
                    "merchid":seller["id",""],
                    "remark":mark_origin["remark\(i)",""]
                ]
            )
            params.removeValue(forKey: "remark\(i)")

            
            let list = DataNode.path(node: "goods", seller, value: NSMutableArray())
            list.list({ (one:NSMutableDictionary, j) in
                let item = [
                    "goodsid":one["goodsid",""],
                    "optionid":one["optionid",""],
                    "total":one["total",""]
                ]
                goods_list.append(item)
            })
        }
        
        
        switch self.buyType {
        case .oneGoods(_):
            params["fromcart"] = "0"
        case .cartGoods(_):
            params["fromcart"] = "1"
        }
        params["goods"] = goods_list.rawJson ?? "[]"
        params["remark"] = marks.rawJson ?? "[]"
        if let mark1 = remark1{
            params["remark1"] = mark1.rawJson ?? "{}"
        }
        
//        print(params.rawJson ?? "")
        submitSend(params: params)
    }
    
    
    func submitSend(params:[String:Any]) {
        let pay_method = PayMethod.method(with: params.mutable_dictionary["paytype","wx"])
        weak var wself = self

        
        HUD.share.show().mode(.indeterminate)
        JoTask().post.log.params(params).log_response()._surl(.订单提交).json_handle { (status, msg, obj, resp) in
            HUD.share.hide(animated: true)
            if status.isSuccess{
                guard let ws = wself else {return}
                switch ws.buyType{
                case .oneGoods(_):
                    __post(notify: Goods.Notice.goodsOrderChange)
                case .cartGoods(_):
                    __post(notify: Goods.Notice.goodsOrderChange)
                    __post(notify: Goods.Notice.goodsCartChage)
                }
                
                if let order = obj as? NSMutableDictionary{
                    let ctr = PayController()
                    switch ws.buyType {
                    case .cartGoods:
                        ctr.task = .cart
                    case .oneGoods:
                        ctr.task = .oneGoods
                        
                    }
                    ctr.mo.model = order
//                    wself?.navigationController?.pushViewController(ctr, animated: true)
                    
                    ctr.presentType = .navRootPresent
                    SCOrderSubmitCtr.orderDetailCtr = nil
                    let nav = RootNavigationController(rootViewController: ctr)
                    weak var wself = self
                    self.navigationController?.present(nav, animated: true, completion: {
                        wself?.popController(1)
                    })
                    return
                }
                
//艾维版本提交订单成功后直接发起支付
//                if let dict = obj as? NSMutableDictionary{
//                    DoPay.pay(pay_method.rawValue, pay_id: dict["product_id",""], task_type: "PayTaskType.goods", dict, finish_block: { (result, task_type, pay_id) in
//                        switch result{
//                        case .ok:
//                            SCOrderSubmitCtr.showPaySuccessResult(order: dict)
//                        case .canle:
//                            break
//                        case .failed(_,_):
//                            SCOrderSubmitCtr.showPayFailedResult(order: dict)
//                        }
//                    })
//                    wself?.showOrderDetail(info: dict)
//                    return
//                }
            }
            msg.alert()
            }.run()
    }
    
    
    override open func mo_request_send() {
        
        var params = [String:Any]()
        switch self.buyType {
        case .oneGoods(let info):
            params = info
        default:
            break
        }
        loadingV.loading()
        weak var wself = self
        JoTask().post._surl(.确认购物信息).params(params).log.log_response().json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                    return
                }
            }
            wself?.mo_request_alert(msg: msg, title: "", bt_title: "")
        }.run()
        
    }
    
    
    
    
    override open func mo_detail_reload() {
        tableView.load(sections: sections, selector: selector)
        
        tableView.model <-- ("section1",sellers,.arrayRefresh)
        tableView.reloadData()
        
        
        self.bottomBar.mo.model = mo.detail
    }
    
    let integralBar = IntegralOptionBar()
    override open func layTable(tableView: UIView) {
        //        super.layTable(tableView: tableView)
        bottomBar.controller = self
        jo_contentView.eelay = [
            [tableView,[ee.T.L.R],[integralBar,ee.T,ee.B]],
            [integralBar,[bottomBar,ee.T,ee.B],[ee.L.R]],
            [bottomBar,[ee.L.B.R]],
        ]
        integralBar.changeMode = {[weak self] (mode,obj)in
            self?.bottomBar.intergalMode = mode
        }
    }
    
    
}


extension SCOrderSubmitCtr{
    
    static var orderDetailCtr:ShoppingOrderDetailCtr? = nil
    
    public static func showPaySuccessResult(order:NSMutableDictionary) {
        co_delay(delay: 0.3) {
            __post(notify: Goods.Notice.goodsOrderChange)
//            print("++++++IIII|=====success pay order")
        }
        
        let ctr = PayController()
      
        ctr.mo.model = order
        ctr.payStatus = .success
        ctr.presentType = .defaultPush
        
        SCOrderSubmitCtr.orderDetailCtr?.navigationController?.pushViewController(ctr, animated: true)
        SCOrderSubmitCtr.orderDetailCtr = nil
    }
    
    static func showPayFailedResult(order:NSMutableDictionary) {
        
        let ctr = PayController()
        ctr.mo.model = order
        ctr.payStatus = .failed
        ctr.presentType = .defaultPush
        SCOrderSubmitCtr.orderDetailCtr?.navigationController?.pushViewController(ctr, animated: true)
        SCOrderSubmitCtr.orderDetailCtr = nil
    }
    
    open func showOrderDetail(info:NSMutableDictionary) {
        switch self.buyType {
        case .cartGoods(_):
            __post(notify: Goods.Notice.goodsCartChage, object: nil, userInfo: nil)
        default:
            break
        }
        let product_id = info["product_id","0"]
        if product_id != "0"
        {
            let ctr = ShoppingOrderDetailCtr()
            ctr.mo.model = ["id":product_id].mutable_dictionary
            ctr.presentType = .navRootPresent
            SCOrderSubmitCtr.orderDetailCtr = ctr
            let nav = RootNavigationController(rootViewController: ctr)
            weak var wself = self
            self.navigationController?.present(nav, animated: true, completion: {
                wself?.popController(1)
            })
        }
        else{
            let ctr = GoodsOrderListCtr()
            ctr.presentType = .navRootPresent
            SCOrderSubmitCtr.orderDetailCtr = nil
            let nav = RootNavigationController(rootViewController: ctr)
            weak var wself = self
            self.navigationController?.present(nav, animated: true, completion: {
                wself?.popController(1)
            })
            
//            if let nav = RTRootNavigationControllerSubClass?.init(rootViewController: ctr){
//                weak var wself = self
//                self.navigationController?.present(nav, animated: true, completion: {
//                    wself?.popController(1)
//                })
//            }
//
           
        }
    }
    
}



